const express = require("express");
const { createServer } = require("http");
const { Server } = require("socket.io");

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
    /* options */
});

const STATE_LEAVE = 0;
const STATE_ENTER = 1;
const STATE_SPEAK = 2;
let port = 55535;
// 管理静态资源
app.use(require("express").static("public"));



/*
    socket表示用户的连接
    socket.emit表示触发了某个事件  发送数据   
    socket.on 表示注册事件 获取数据

    io.emit  广播事件

    第一个参数是自定义事件名。后面是一个回调函数
*/

let count = 0;
io.on("connection", (socket) => {
    // ...
    count++;
    // 广播当前人数
    io.emit("count", count);
    // 获取用户的用户名
    socket.on("username", (data) => {
        socket.username = data;
        // console.log(data);
        io.emit("somebodyEnter", {
          username : socket.username,
          state: STATE_ENTER
        });
    });

    

    // 监听该用户的发言
    socket.on("speak", (data) => {
        // 广播
        io.emit("somebodySpeak", {
            username: socket.username,
            speak: data,
            headImage: socket.headImage,
            state: STATE_SPEAK,
        });
    });


    // 获取用户的头像
    socket.on("sendHeadImg", (data) => {
      socket.headImage = data;
    })

    // 断开连接
    socket.on('disconnect', function(){
      io.emit("somebodyLeave", {
        username : socket.username,
        state: STATE_LEAVE
      });
      count--;
      io.emit("count", count);
  });
});

httpServer.listen(port, function(){
  console.log(`当前监听${port}端口`);
});

app.get("/", function (req, res) {
  res.redirect("/index.html");
});